package com.hujun.common.memcached.core;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import net.spy.memcached.MemcachedClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpyMemcached implements Memcached {

	private MemcachedClient memcachedClient;
	private static final int EXP = 3600;
	private static final Logger log = LoggerFactory.getLogger(SpyMemcached.class);
	
	public SpyMemcached(){}
	public SpyMemcached(MemcachedClient memcachedClient){
		this.memcachedClient = memcachedClient;
	}
	
	public boolean add(String key, Object value) {
		if(null == key || null == value){
			return false;
		}
		Future<Boolean> future = memcachedClient.add(key, EXP, value);
		try {
			return future.get(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("add error!key=" + key + "| value=" + value);
			return false;
		}
	}

	public boolean add(String key, Object value, Integer expire) {
		if(null == key || null == value || null == expire){
			return false;
		}
		Future<Boolean> future = memcachedClient.add(key, expire, value);
		try {
			return future.get(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("add error!key=" + key + "| value=" + value);
			return false;
		}
	}

	public Object get(String key) {
		if(null == key ){
			return false;
		}
		return memcachedClient.get(key);
	}

	public boolean replace(String key, Object value) {
		if(null == key || null == value){
			return false;
		}
		Future<Boolean> future = memcachedClient.replace(key, EXP, value);
		try {
			return future.get(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("replace error!key=" + key + "| value=" + value);
			return false;
		}
	}

	public boolean replace(String key, Object value, Integer expire) {
		if(null == key || null == value || null == expire){
			return false;
		}
		Future<Boolean> future = memcachedClient.replace(key, expire, value);
		try {
			return future.get(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("replace error!key=" + key + "| value=" + value);
			return false;
		}
	}

	public MemcachedClient getMemcachedClient() {
		return memcachedClient;
	}

	public void setMemcachedClient(MemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	public boolean delete(String key) {
		if(null == key){
			return false;
		}
		Future<Boolean> future = memcachedClient.delete(key);
		try {
			return future.get(3,TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("delete error!key=" + key);
			return false;
		}
	}


}
